package com.zdb.n1.controller;

import com.zdb.n1.entity.ExerciseType;
import com.zdb.n1.payload.response.MessageResponse;
import com.zdb.n1.service.ExerciseTypeService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/exercise-types")
public class ExerciseTypeController {

    @Autowired
    private ExerciseTypeService exerciseTypeService;

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ExerciseType> createExerciseType(@Valid @RequestBody ExerciseType exerciseType) {
        return ResponseEntity.ok(exerciseTypeService.saveExerciseType(exerciseType));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ExerciseType> updateExerciseType(
            @PathVariable Long id, 
            @Valid @RequestBody ExerciseType exerciseType) {
        ExerciseType existingType = exerciseTypeService.getExerciseTypeById(id);
        exerciseType.setId(existingType.getId());
        return ResponseEntity.ok(exerciseTypeService.saveExerciseType(exerciseType));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ExerciseType> getExerciseTypeById(@PathVariable Long id) {
        return ResponseEntity.ok(exerciseTypeService.getExerciseTypeById(id));
    }

    @GetMapping("/by-name/{name}")
    public ResponseEntity<ExerciseType> getExerciseTypeByName(@PathVariable String name) {
        return ResponseEntity.ok(exerciseTypeService.getExerciseTypeByName(name));
    }

    @GetMapping
    public ResponseEntity<List<ExerciseType>> getAllExerciseTypes() {
        return ResponseEntity.ok(exerciseTypeService.getAllExerciseTypes());
    }

    @GetMapping("/by-category/{category}")
    public ResponseEntity<List<ExerciseType>> getExerciseTypesByCategory(
            @PathVariable ExerciseType.Category category) {
        return ResponseEntity.ok(exerciseTypeService.getExerciseTypesByCategory(category));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<MessageResponse> deleteExerciseType(@PathVariable Long id) {
        return ResponseEntity.ok(exerciseTypeService.deleteExerciseType(id));
    }
}